package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.example.context.BaseContext;
import org.example.mapper.ExhibitionMapper;
import org.example.mapper.FeedbackMapper;
import org.example.mapper.ReservationMapper;
import org.example.pojo.domain.Exhibition;
import org.example.pojo.domain.Reservation;
import org.example.pojo.vo.ReservationVo;
import org.example.pojo.vo.ReservationWithFeedbackVo;
import org.example.service.ReservationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ReservationServiceImpl implements ReservationService {

    @Autowired
    private ReservationMapper reservationMapper;
    @Autowired
    private ExhibitionMapper exhibitionMapper;
    @Autowired
    private FeedbackMapper feedbackMapper;

    @Override
    public int getVisitorsCount() {
        return reservationMapper.countConfirmedVisitorsByDate(new Date());
    }

    @Override
    public PageInfo<ReservationVo> listReservationsByUser(int userId, int page, int size) {
        // 1. 分页
        PageHelper.startPage(page, size);
        List<Reservation> list = reservationMapper.listByUser(userId);
        PageInfo<Reservation> pi = new PageInfo<>(list);

        // 2. 转为 Vo 并附带 Exhibition
        List<ReservationVo> voList = list.stream().map(res -> {
            ReservationVo vo = new ReservationVo();
            BeanUtils.copyProperties(res, vo);
            Exhibition ex = exhibitionMapper.selectById(res.getExhibitionId());
            vo.setExhibition(ex);
            return vo;
        }).collect(Collectors.toList());

        // 3. 将 voList 放回 PageInfo
        PageInfo<ReservationVo> voPage = new PageInfo<>();
        // 复制分页属性
        voPage.setPageNum(pi.getPageNum());
        voPage.setPageSize(pi.getPageSize());
        voPage.setTotal(pi.getTotal());
        voPage.setPages(pi.getPages());
        voPage.setList(voList);
        return voPage;
    }

    @Override
    public PageInfo<ReservationVo> listReservationsByStatus(int userId, String status, int page, int size) {
        // 1. 分页查询预约记录
        PageHelper.startPage(page, size);
        List<Reservation> reservations = reservationMapper.listByStatus(userId, status);
        PageInfo<Reservation> pi = new PageInfo<>(reservations);

        // 2. 将查询结果转换为 ReservationDto 并附带展览信息
        List<ReservationVo> dtoList = reservations.stream().map(reservation -> {
            ReservationVo dto = new ReservationVo();
            BeanUtils.copyProperties(reservation, dto);
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            dto.setExhibition(exhibition);
            return dto;
        }).collect(Collectors.toList());

        // 3. 将转换后的结果放入 PageInfo
        PageInfo<ReservationVo> dtoPage = new PageInfo<>();
        BeanUtils.copyProperties(pi, dtoPage);
        dtoPage.setList(dtoList);

        return dtoPage;
    }

    @Override
    public PageInfo<ReservationWithFeedbackVo> listCompletedWithFeedback(int userId, String status, int page, int size) {
        // 1. 分页查询预约记录
        PageHelper.startPage(page, size);
        List<Reservation> reservations = reservationMapper.listByStatus(userId, status);
        PageInfo<Reservation> pi = new PageInfo<>(reservations);

        // 2. 将查询结果转换为 ReservationWithFeedbackVo 并附带展览信息
        List<ReservationWithFeedbackVo> voList = reservations.stream().map(reservation -> {
            ReservationWithFeedbackVo vo = new ReservationWithFeedbackVo();
            BeanUtils.copyProperties(reservation, vo);
            Exhibition exhibition = exhibitionMapper.selectById(reservation.getExhibitionId());
            vo.setExhibition(exhibition);
            int count = feedbackMapper.countByUserAndExhibition(userId, reservation.getExhibitionId());
            if (count>0){
                vo.setHasFeedback(true);
            }else {
                vo.setHasFeedback(false);
            }
            return vo;
        }).collect(Collectors.toList());

        // 3. 将转换后的结果放入 PageInfo
        PageInfo<ReservationWithFeedbackVo> voPage = new PageInfo<>();
        BeanUtils.copyProperties(pi, voPage);
        voPage.setList(voList);

        return voPage;
    }

    @Override
    public boolean hasFeedbackForReservation(Integer exhibitionId) {
        int userId = Integer.valueOf(BaseContext.getCurrentId());
        int count = feedbackMapper.countByUserAndExhibition(userId, exhibitionId);
        return count>0;
    }



    @Override
    public List<Reservation> listReservationsByUser(Integer userId) {
        return reservationMapper.findByUserId(userId);
    }

    @Override
    public void makeReservation(Reservation reservation) {
        reservation.setUserId(Integer.valueOf(BaseContext.getCurrentId()));
        // 如果当天已经预约过了，就不能预约了
        // 1. 检查当天是否已预约，只统计未取消的预约
        int todayCount = reservationMapper.countByUserIdAndDateAndNotCancelled(
                reservation.getUserId(),
                reservation.getReservedTime()
        );
        if (todayCount > 0) {
            throw new RuntimeException("您那天已有未取消的预约，不能重复预约。");
        }

        // 2. 如果没预约过，才执行插入
        reservationMapper.insertReservation(reservation);
    }

    @Override
    public void cancelReservation(Integer reservationId) {
        reservationMapper.updateReservationStatus(reservationId, "cancelled");
    }

    @Override
    public Reservation getReservationDetails(Integer reservationId) {
        return reservationMapper.findById(reservationId);
    }

    @Override
    @Transactional
    public void markReservationAsCompleted(Integer reservationId) {
        // 更新预约状态为 "completed"
        reservationMapper.updateReservationStatus(reservationId, "completed");
    }
}
